<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      //封装Vue构造函数
      function Vue({ data }) {
        this._data = data;

        //  数据代理
        for (let key in this._data) {
          Object.defineProperty(this, key, {
            get: function ProxyGetter() {
              return this._data[key];
            },
            set: function ProxySetter(value) {
              this._data[key] = value;
            },
          });
        }

        // 数据劫持
        for (let key in this._data) {
          let value = this._data[key];
          observe(this._data, key, value);
        }

        function observe(obj, key, value) {
          if (typeof value === Object && value !== null) {
            for (let _key in value) {
              let _value = value[key];

              observe(value, _key, _value);
            }
          }

          defineReactive(obj, key, value);
        }

        function defineReactive(obj, key, value) {
          Object.defineProperty(obj, key, {
            get: function reactiveGetter() {
              console.log("劫持了读取数据");
              return value;
            },
            set: function reactiveSetter(val) {
              console.log("劫持了修改数据");
              return (value = val);
            },
          });
        }
      }

      //实例化Vue
      const vm = new Vue({
        data: {
          name: "laowang",
          age: 18,
          sex: "男",
        },
      });
      console.log(vm, "vm");
    </script>
  </body>
</html>
